/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2015-2018. All rights reserved.
 * Description: Signature Verify CBB Library
 * Author: tangzonglei
 * Create: 2015
 * History: 2018/11/23 yebin code rule fixes
 */
#include "../cmscbb_common/cmscbb_buf.h"
#include "cmscbb_err_def.h"

CMSCBB_ERROR_CODE CmscbbBufInit(CmscbbBuf* buf, const CVB_BYTE* val, CVB_UINT32 valLen)
{
    if ((buf == CVB_NULL) || (val == CVB_NULL) || (valLen == 0)) {
        return CMSCBB_ERR_CONTEXT_INVALID_PARAM;
    }

    buf->val = val;
    buf->bufLen = valLen;
    buf->cursor = 0;

    return CVB_SUCCESS;
}

CMSCBB_ERROR_CODE CmscbbBufGet(CmscbbBuf* buf, CVB_BYTE* byte)
{
    if (buf == CVB_NULL || byte == CVB_NULL) {
        return CMSCBB_ERR_CONTEXT_INVALID_PARAM;
    }

    /* nBufLen < 2M , So it won't overflow. */
    if (buf->cursor == buf->bufLen) {
        return CMSCBB_ERR_SYS_BUF_EOF;
    }

    *byte = buf->val[buf->cursor++];
    return CVB_SUCCESS;
}

CMSCBB_ERROR_CODE CmscbbBufSeek(CmscbbBuf* buf, CVB_INT32 pos, CmscbbBufSeekWay way)
{
    CVB_INT32 newPos;

    if (buf == CVB_NULL) {
        return CMSCBB_ERR_CONTEXT_INVALID_PARAM;
    }

    if (way != CBSW_CURRENT) {
        return CMSCBB_ERR_UNDEFINED;
    }

    newPos = (CVB_INT32)buf->cursor + pos;
    if (newPos < 0 || newPos > (CVB_INT32)buf->bufLen) { /* newPos < 0 : Prevent overflow symbol reversal */
        return CMSCBB_ERR_UNDEFINED;
    }
    buf->cursor = (CVB_UINT32)newPos;

    return CVB_SUCCESS;
}
